<script setup name="p-switch">
const emit = defineEmits()
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  label: {
    type: String,
    default: '',
  },
  beforeChange: {
    type: Function,
  },
  active: { type: String || Number, default: '0' },
  inactive: { type: String || Number, default: '1' },
})

const data = ref(1)
const load = ref(false)
watch(
  () => props.modelValue,
  (val, load) => {
    data.value = String(val)
  },
  { deep: true, immediate: true }
)

watch(
  () => data.value,
  (val) => {
    emit('update:modelValue', val)
  },
  { deep: true }
)

const change = (val) => {
  if (load.value) emit('change', val)
}
onMounted(() => {
  if (typeof props.active != 'string')
    throw new Error('p-switch组件:active类型只能是string')
  if (typeof props.inactive != 'string')
    throw new Error('p-switch组件:inactive类型只能是string')
  load.value = true
})
</script>

<template>
  <div class="flex-item-center">
    <label style="margin-right: 10px">{{ props.label }}</label>
    <el-switch
      @change="change"
      :disabled="props.disabled"
      v-model="data"
      :active-value="props.active"
      :inactive-value="props.inactive"
    />
  </div>
</template>
